<script setup>
import { onMounted, reactive,toRefs } from 'vue';
import { getNamespaceListHandler } from '../../api/namespace.js';
import { getClusterListHandler } from '../../api/cluster.js';
import { useRoute } from 'vue-router';

const route = useRoute()

const props = defineProps({
    showNamespace: {
        tupe: Boolean,
        default: true
    },
})


const data = reactive({
    clusterList: [],
    namespaceList: [],
    clusterId: "",
    namespace: ""
})

// 定义两个个事件，用来处理当集群和namespace产生变化后，应该做哪些处理
const emits = defineEmits(['clusterChangedRollback', 'namespaceChangedRollback'])
// 定义namespace发生变化需要做的事情
const namespaceChangedRollbackHandler = () => {
    emits('namespaceChangedRollback', data.clusterId, data.namespace)
} 
const clusterChangedRollbackHandler = () => {
    emits('clusterChangedRollback', data.clusterId)
} 

// 查询集群列表
const getNamespaceList= async() =>{
    await getNamespaceListHandler(data.clusterId).then((response)=>{
        console.log("response:", response.data.data.items)
        data.namespaceList = response.data.data.items.items
    })
    const curNamespace = route.query.namespace
    data.namespace = curNamespace?curNamespace:"default"
    // 回调
    namespaceChangedRollbackHandler()

}

// 异步转成同步
const getClusterList = async() => {
    await getClusterListHandler().then(
        (res) => {
            data.clusterList = res.data.data.items
        }
    )
}   

const clusterChanged = () => {
    // 查询namespace
    if (props.showNamespace) {
        getNamespaceList()
    } else {
        clusterChangedRollbackHandler()
    }
}

const namespaceChanged = () => {
    namespaceChangedRollbackHandler()
}

onMounted(async() => {
    await getClusterList()
    const defaultClusterSelected = data.clusterList[0].id
    // 获取当前请求是否携带了集群ID的参数
    const curClusterId = route.query.clusterId
    data.clusterId = curClusterId?curClusterId:defaultClusterSelected
    clusterChanged()

    
})

const {clusterId,clusterList,namespace,namespaceList} = toRefs(data)
</script>



<template>
    <el-select filterable v-model="clusterId" placeholder="选择集群" @change="clusterChanged()" style="width: 340px;">
        <el-option v-for="item in clusterList"
        :key="item.id"
        :label="item.id"
        :value="item.id"
        :disabled="item.status == 'InActive'"
        />
    </el-select>

    <el-select filterable style="margin-left: 20px;" v-if="props.showNamespace" v-model="namespace" placeholder="选择namespace" @change="namespaceChanged()">
        <el-option v-for="items in namespaceList"
        :key="items.metadata.name"
        :label="items.metadata.name"
        :value="items.metadata.name"
        />
    </el-select>

</template>


